package java_thinking.unit_17._17_9_10;

import java_thinking.unit_17._17_2_6.Countries;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

/**
 * @Desc:   实现clear与remove
 * @author: cww
 * @DateTime: 2019/4/19 20:32
 */

public class SimpleHashMap2<K,V> extends SimpleHashMap<K,V> {
    @Override
    public void clear() {
        buckets = new LinkedList[SIZE];
    }

    @Override
    public V remove(Object key) {
        int index = Math.abs(key.hashCode()) % SIZE;
        if (buckets[index] == null) {
            return null;
        }
        Iterator<SlowMap.MapEntry<K,V>> it = buckets[index].iterator();
        while (it.hasNext()) {
            SlowMap.MapEntry<K,V> iPair = it.next();
            if (iPair.getKey().equals(key)) {
                V value = iPair.getValue();
                it.remove();
                return value;
            }
        }
        return null;
    }

    public static void main(String[] args) {
        SimpleHashMap2<String,String> m =
                new SimpleHashMap2<String,String>();
        m.putAll(Countries.capitals(10));
        System.out.println(m);
        System.out.println("m.get(\"BURUNDI\") = "+ m.get("BURUNDI"));
        m.remove("BURUNDI");
        System.out.println("After removal, m.get(\"BURUNDI\") = "+ m.get("BURUNDI"));
        m.clear();
        System.out.println("After clearing: " + m);
        Map<String, String> map = new HashMap<>(16);
    }
}
